from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.cache import cache
from django.views import View
from apps.areas.models import Area
from django.http.response import JsonResponse
from utils.response_code import RETCODE


class Areas(LoginRequiredMixin, View):
    def get(self, request):
        area_id = request.GET.get('area_id')
        if area_id is not None:
            sub_list = Area.objects.filter(parent=area_id)
            subs = []
            for sub in sub_list:
                subs.append({
                    'id': sub.id,
                    'name': sub.name
                })
            context = {
                'code': RETCODE.OK,
                'errmsg': 'ok',
                'subs': subs
            }
            return JsonResponse(context)
        else:
            provinces = cache.get('provinces')
            if provinces is None:
                province_list = Area.objects.filter(parent__isnull=True)
                provinces = []
                for province in province_list:
                    provinces.append({
                        'id': province.id,
                        'name': province.name
                    })
                cache.set('provinces', provinces, 24*3600)
            context = {
                'code': RETCODE.OK,
                'errmsg': 'ok',
                'provinces': provinces
            }
            return JsonResponse(context)




